use std::{collections::HashMap, convert::Infallible};

use hyper::header;
use serde_json::json;

use crate::client::create_client;

pub async fn buy_instruction(
    mut query: HashMap<String, String>,
) -> Result<warp::reply::WithHeader<warp::reply::WithHeader<warp::reply::Json>>, Infallible> {
    query.insert(
        "rtimestamp".to_string(),
        chrono::Utc::now()
            .to_string()
            .replace("UTC", "")
            .replace('+', ""),
    );

    let data = match create_client(None)
        .unwrap()
        .get("https://api-mainnet.magiceden.io/v2/instructions/buy_now")
        .header(header::ACCEPT, "application/json")
        .header(header::ORIGIN, "https://magiceden.io")
        .header(header::REFERER, "https://magiceden.io")
        .query(&query)
        .send()
        .await
    {
        Ok(value) => match value.json().await {
            Ok(value) => value,
            Err(_) => json!({}),
        },
        Err(_) => json!({}),
    };

    let reply = warp::reply::json(&data);

    Ok(warp::reply::with_header(
        warp::reply::with_header(reply, "Access-Control-Allow-Origin", "*"),
        "Access-Control-Allow-Headers",
        "*",
    ))
}
